/*
 * @Description:
 * @Author: Yong
 * @Date: 2021-09-29 17:06:09
 * @LastEditTime: 2021-09-29 23:55:25
 */

import { ResOp } from "../interface"
import ERROR_CONSTANTS from "./error_constants"

class ResHandler {

    private resHandle(resData: ResOp, statusCode = 200) {
        const json = {
            ...resData,
            isSuccess: resData.isSuccess,
            msg: resData?.code ? this.getErrorMessageByCode(resData!.code) || resData?.msg || 'unknown error' : resData?.msg || 'success',
            data: resData.data || null
        }
        if (resData.isSuccess && resData.data) json.data = resData.data
        return json
    }

    /**
    * 根据code获取错误信息
    */
    private getErrorMessageByCode(code: number): string {
        return ERROR_CONSTANTS[code]
    }

    public successRes (data?: any): ResOp {
        return this.resHandle({ msg: 'ok', isSuccess: true, data }, 200)
    }
    
    public errorRes (config?: { msg?: string, code?: number, data?: any }, statusCode?: number) {
        config = config || { msg: 'request Error', code: -1 }
        return this.resHandle({
            msg: config.msg,
            code: config.code,
            data: config.data,
            isSuccess: false,
        })
    }
}
export const resHandler = new ResHandler()